<?php
/**
 * Model de leads.
 *
 * @author    Chavão <freela@chavao.net>
 * @copyright Copyright (c) 2011, Chavão
 * @version   0.1
 */

require_once 'campanha.php';

class Lead extends AppModel
{
    private $p_arrLead = array();
    private $p_iLeadsAtendidos = 0;
    private $p_arrStatusUsados = array();
    private $p_iTotalVendas = 0;
    private $p_sSomaDtMenor = 0;
    private $p_sSomaDtMaior = 0;
    private $p_arrCampValor = array();

    public function adicionar( $arrData, $pbAdmin = true )
    {
        $objLogLeadControlModel = new LogLeadControl();
        date_default_timezone_set('America/Sao_Paulo');
        $arrData['lead_entrada'] = date('Y-m-d H:i:s');
        $arrData['lead_status'] = 1; // Status: Em aberto
        if(isset($arrData['lead_nascimento']))
            $arrData['lead_nascimento'] = inverterData( $arrData['lead_nascimento'],'-' );
        if( !$pbAdmin ) 
            $arrData['usua_id'] = $_SESSION['usua_id'];
        $this->save( $arrData );
        $objLogLeadControlModel->gravarLog('lead','novo lead',"lead_id:".$this->getInsertId());
    }

    public function buscarLeads( $psCriterio, $psUser = 'USER', $piPage )
    {

        $iUsuaId = $_SESSION['usua_id'];
            
        $objCampanhaModel = new Campanha();
        $arrCamp = $objCampanhaModel->listarTodasCampanhasLeads();

        $sInCamp = '';
        foreach( $arrCamp as $objCamp )
        {
            $objCamp = (object) $objCamp;

            $sInCamp .= $objCamp->camp_id.',';

            $this->p_arrCampValor[$objCamp->camp_id] = array(0=>$objCamp->camp_valor,1=>0);
        }

        $sInCamp = substr($sInCamp,0,-1);

        if( trim( $psCriterio ) != '' )
        {  
            if( $psUser == 'ADMIN' ) $arrConditions = array('camp_id IN ('.$sInCamp.')', $psCriterio);
            else $arrConditions = array('usua_id' => $iUsuaId, $psCriterio);
        }
        else
        {
            if( $psUser == 'ADMIN' ) $arrConditions = array('camp_id IN ('.$sInCamp.')');
            else $arrConditions = array('usua_id' => $iUsuaId,'(1=1)');
        }

        if( !isset( $_SESSION['paginate_exibir'] ) )
        {
            $_SESSION['paginate_exibir'] = CHAV_PAGINATE;
        }

        $iPaginateExibir = $_SESSION['paginate_exibir'];
        
        $arrLead = $this->paginate(array(
				'page' => $piPage,
				'perPage' => $iPaginateExibir,
				'conditions' => $arrConditions,
				'order' => 'lead_id DESC'
				));

        $iContador = ( $piPage > 1 ) ? ( ( $iPaginateExibir * $piPage ) - $iPaginateExibir ) : 0;
        if( !$arrLead ) $arrLead = array();

        foreach( $arrLead as $k => $objLead )
        {
            $objLead = (object) $objLead;

            if($objLead->lead_status != 1)
            {
                ++$this->p_iLeadsAtendidos;
            }
            // Pegar data de lead_entrada e tirar diferença até lead_atendimento
            $dtMenor = $objLead->lead_entrada;
            $dtMaior = $objLead->lead_atendimento;

            $objLead->tempo_resposta = ( trim( $dtMaior ) != '' ) ? difData( $dtMaior, $dtMenor ) : '-';
           

            $arrLead[$k] = $objLead;

            
            if($objLead->lead_status!=1)
            {
                $this->p_sSomaDtMaior += strtotime($dtMaior);
                $this->p_sSomaDtMenor += strtotime($dtMenor);
            }
            
            // Criar gráfico
            if(isset($this->p_arrStatusUsados[$objLead->lead_status]))
                $this->p_arrStatusUsados[$objLead->lead_status] += 1;
            else
                $this->p_arrStatusUsados[$objLead->lead_status] = 1;

            // Calcular total de valor de venda
            $this->p_iTotalVendas += 10;//$objLead->lead_valor_venda;

            // Calcular valor do lead ((campanha)/(número de leads)) VER ISSO AQUI!
            if(isset($this->p_arrCampValor[$objLead->camp_id][1]))
                $this->p_arrCampValor[$objLead->camp_id][1] += 1;
            else
                $this->p_arrCampValor[$objLead->camp_id][1] = 1;

        }

        $this->p_arrLead = $arrLead;

        return $this->p_arrLead;
    }

    public function totalLeads()
    {
        return sizeof( $this->p_arrLead );
    }

    public function totalLeadsAtendidos()
    {
        return $this->p_iLeadsAtendidos;
    }

    public function statusUsados()
    {
        return $this->p_arrStatusUsados;
    }

    public function totalVendas()
    {
        return $this->p_iTotalVendas;
    }

    public function tempoMedio()
    {
        if( $this->p_iLeadsAtendidos < 1 )
        {
            $this->p_sSomaDtMaior = 0;
            $this->p_sSomaDtMenor = 0;
        }
        else
        {
            $this->p_sSomaDtMaior = $this->p_sSomaDtMaior / $this->p_iLeadsAtendidos;
            $this->p_sSomaDtMenor = $this->p_sSomaDtMenor / $this->p_iLeadsAtendidos;
        }

        return difData( $this->p_sSomaDtMaior, $this->p_sSomaDtMenor, true );
    }

    /**
     * Gera JSON para exibição do gráfico baseado no status do lead.
     * @access private
     * @return string JSON
     */
    public function montarJSONGrafico( $parrStatus )
    {
        $arrColorStatus =  array(1=>'#009900', 2=>'#33CCFF', 3=>'#FF9900', 4=>'#FFFF00', 5=>'#CC0000');
        $arrStatusUsados = $this->statusUsados();
        $iTotalLeads = $this->totalLeads();

        $sSliceChart = '';
                
        if( $iTotalLeads > 0 )
        {   
            foreach( $parrStatus as $sChave => $sValor )
            {
                if(isset($arrStatusUsados[$sChave]))
                {
                    $iPorcent = bcdiv( ( $arrStatusUsados[$sChave]*100 ), $iTotalLeads, 2 );

                    if( $iPorcent > 0 )
                    {
                        $sSliceChart .= "{ name: '".$sValor."',  y: ".$iPorcent.", color: '".$arrColorStatus[$sChave]."' },";
                    }
                }
                
            }
        }
 
        return substr($sSliceChart, 0, -1);
    }

    public function valorLead()
    {
        
        $iSomaCamp = 0;
        $iSomaLeads = 0;
        foreach( $this->p_arrCampValor as $sCampId => $arrValor)
        {
            
            if( $arrValor > 0 )
            {
                $iSomaCamp += $arrValor[0];
                $iSomaLeads += $arrValor[1];
            }
        }

        return ( $iSomaLeads > 0 ) ? (int) ($iSomaCamp / $iSomaLeads) : 0;
    }
    /**
     * Verifica se o número de leads está dentro do limite contratado
     * @autor Fernanda Rebelatto
     * @access public
     * @return bool
     */
    public function podeAddLead()
    {
        $objPlanoModel = new Plano();
        $objCampanhaModel = new Campanha();
        $arrCamp = $objCampanhaModel->listarTodasCampanhasLeads();
        $oPlano = $objPlanoModel->planoCliente($_SESSION['plano_id']);
                
        $_SESSION['plan_campanhas'] = $oPlano['plan_campanhas'];
        $_SESSION['plan_usuarios'] = $oPlano['plan_usuarios'];
        $_SESSION['plan_leads'] = $oPlano['plan_leads'];
        $intLeads = 0;
        foreach ($arrCamp as $oCampanha) 
        {
             $intLeads = $intLeads + $this->count(array(
                    'conditions' => array( 'camp_id' => $oCampanha['camp_id'] )
             ));
        }
        
        return ($_SESSION['plan_leads'] > $intLeads);
    } 
    public function leadsBloqueadosCliente($piClieId, $limitBusca)
    {          
        $objCampanhaModel = new Campanha();
        $arrCamp = $objCampanhaModel->listarTodasCampanhasLeads($piClieId);

        $sInCamp = '';
        foreach( $arrCamp as $objCamp )
        {
            $objCamp = (object) $objCamp;

            $sInCamp .= $objCamp->camp_id.',';

            $this->p_arrCampValor[$objCamp->camp_id] = array(0=>$objCamp->camp_valor,1=>0);
        }

        $sInCamp = substr($sInCamp,0,-1);

        
        $arrConditions = array('camp_id IN ('.$sInCamp.')', "lead_bloqueado = '1'");

        $this->limit = $limitBusca;
        $this->order = 'lead_entrada ASC';
   
        $arrLeadsBloqueados = $this->all(array(
            'conditions' => $arrConditions
        ));            
        $this->limit = null;
        $this->order = null;
     
        return $arrLeadsBloqueados;
    }  
    public function temLeadBloqueado($piClieId)
    {
        $objCampanhaModel = new Campanha();
        $arrCamp = $objCampanhaModel->listarTodasCampanhasLeads($piClieId);

        $sInCamp = '';
        foreach( $arrCamp as $objCamp )
        {
            $objCamp = (object) $objCamp;

            $sInCamp .= $objCamp->camp_id.',';

            $this->p_arrCampValor[$objCamp->camp_id] = array(0=>$objCamp->camp_valor,1=>0);
        }

        $sInCamp = substr($sInCamp,0,-1);
        $arrConditions = array("camp_id IN (".$sInCamp.")", "lead_bloqueado = '1'");
        $arrLead = $this->first(array(
				'conditions' => $arrConditions
				));
        return (count($arrLead)>0);

    }
    public function quantidadeLeadDesbloqueado($piClieId)
    {
        $objCampanhaModel = new Campanha();
        $arrCamp = $objCampanhaModel->listarTodasCampanhasLeads($piClieId);

        $sInCamp = '';
        foreach( $arrCamp as $objCamp )
        {
            $objCamp = (object) $objCamp;

            $sInCamp .= $objCamp->camp_id.',';

            $this->p_arrCampValor[$objCamp->camp_id] = array(0=>$objCamp->camp_valor,1=>0);
        }

        $sInCamp = substr($sInCamp,0,-1);
        $arrConditions = array("camp_id IN (".$sInCamp.")", "lead_bloqueado = '0'");
        $nLeadsDesbloqueados = $this->count(array(
				'conditions' => $arrConditions
				));
        return $nLeadsDesbloqueados;

    }
}
        
?>